﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace sqlsearcher.Models
{
    public class HttpSave
    {
        public static string directoryPath = Application.StartupPath + "\\Http";
        public static void Write<T>(T t, string fileName) where T:HttpEntity
        {
            fileName = fileName.Replace(new Uri(fileName).Host, "").Replace("http://", "").Replace("https://", "");
            fileName = fileName.Replace("/", "_");
            if (fileName.LastIndexOf("?") != -1)
                fileName = fileName.Substring(0, fileName.LastIndexOf("?"));
            fileName = fileName.Substring(1, fileName.Length - 1);
            fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + " " + fileName;
            var filePath = Application.StartupPath + "\\Http\\" + fileName + ".json";
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            using (StreamWriter sw = new StreamWriter(filePath))
            {
                var writeEntity = Activator.CreateInstance<HttpEntityFormat>();
                writeEntity.HttpContentType = t.HttpContentType;
                writeEntity.HttpMethod = t.HttpMethod;
                writeEntity.HttpRequestTime = t.HttpRequestTime;
                writeEntity.HttpResponseContent = JsonConvert.DeserializeObject(t.HttpResponseContent);
                writeEntity.HttpUrl = t.HttpUrl;

                if (HttpClient.ConvertJsonString(t.Data.ToString()).Result.Item1)
                    writeEntity.Data = JsonConvert.DeserializeObject(t.Data.ToString());
                else
                    writeEntity.Data = t.Data.ToString();

                var writeEntityJson = JsonConvert.SerializeObject(writeEntity);
                writeEntityJson = HttpClient.ConvertJsonString(writeEntityJson).Result.Item2; 

                sw.Write(writeEntityJson);
            }
        }

        public static List<T> Reader<T>(string filename)
        {
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
                return new List<T>();
            }
            var files = new string[0];
            
            if (!string.IsNullOrWhiteSpace(filename))
            {
                if (filename.IndexOf("?") != -1)
                {
                    filename = filename.Substring(0, filename.LastIndexOf("?"));
                }
                files = Directory.GetFiles(directoryPath, "*"+filename+"*");
            }
            else
            {
                files = Directory.GetFiles(directoryPath);
            }
            if (files == null || files.Count() <= 0)
                return null;

            var longArr = new List<long>();
            for (var i = 0; i < files.Length; i++)
            {
                var value = files[i].Substring(files[i].LastIndexOf("\\") + "\\".Length, files[i].IndexOf(" ") - files[i].LastIndexOf("\\"));
                var longItem = long.Parse(value);
                if (!longArr.Contains(longItem))
                    longArr.Add(longItem);
            }
            longArr = longArr.OrderByDescending(m => m).ToList();

            var ts = new List<T>();
            var fileList = files.ToList();
            for (int i = 0; i < longArr.Count; i++)
            {
                var fileItem = fileList.Find(m => m.IndexOf(longArr[i].ToString()) != -1);
                if (fileItem == null)
                    continue;

                using (var sr = new StreamReader(fileItem))
                {
                    ts.Add(JsonConvert.DeserializeObject<T>(sr.ReadToEnd()));
                }

            }
            return ts;
        }

        internal static void Clear()
        {
            var files = Directory.GetFiles(directoryPath);
            if (files == null || files.Count() <= 0)
                return ;
            foreach (var item in files)
            {
                if (File.Exists(item))
                {
                    File.Delete(item);
                }
            }
        }
    }
}
